# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.template.loader import get_template
from django.template import Template, Context
from django.http import HttpResponseRedirect
from PSM.PSMDatabase.models import *
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django import forms
import math


#############################(by Porngsathorn Surikan)#########################
def teacher_form(request):
    return render_to_response('teacher_form.html')


def teacher(request):
    username = request.GET['username']
    password = request.GET['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
                login(request, user)
                userDetail = request.user
                url = request.get_host()
                t = get_template('teacher_main.html')
                html = t.render(Context({'URL': url, 'USER': userDetail}))
                return HttpResponse(html)
        else:
                return render_to_response('teacher_form_err.html')
    else:
        return render_to_response('teacher_form_err.html')


#########################  ADD STUDENT (by Sombut Poolsawat)###################
def addStudent_form(request):
    # Check authenticate.
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    url = request.get_host()
    userDetail = request.user
    t = get_template('add_student_form.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


def addStudent(request):
    # Check authenticate.
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        errors = []  # Variable declarations : error type list
        if 'id_student' in request.GET and request.GET['id_student']\
        and 'firstname' in request.GET and request.GET['firstname'] \
        and 'lastname' in request.GET and request.GET['lastname'] \
        and 'section' in request.GET and request.GET['section']:
                u = User.objects.get(username__exact=request.user)
                teacher = u.get_full_name()
                # Keep value received
                id_student_in = request.GET['id_student']
                firstName_in = request.GET['firstname']
                lastname_in = request.GET['lastname']
                section_in = request.GET['section']
                # check to ensure that student have.
                if DetailStudent.objects.filter(\
                studentID=id_student_in):
                    userDetail = request.user
                    url = request.get_host()
                    errors.append('ID Student this Repeatedly.')
                    # show error and add new student
                    return render_to_response('add_student_form.html',\
                    {'errors': errors, 'URL': url, 'USER': userDetail})
                # ensure that no student have
                else:
                    # crete Detail Student
                    dataInput = DetailStudent.objects.create(\
                    studentID=id_student_in, firstName=firstName_in, \
                    lastName=lastname_in, section=section_in,\
                    teacherName=teacher, labScore="null", midScore="null", \
                    finalScore="null", totalScore="null", \
                    gradeScore="null")
                    userDetail = request.user
                    # save Detail Student
                    dataInput.save()
                    url = request.get_host()
                    # show add student result
                    return render_to_response('add_student_result.html',\
                    {'URL': url, 'STUDENTS': dataInput, 'USER': userDetail})
        # the data get incomplete
        else:
                userDetail = request.user
                url = request.get_host()
                errors.append('Please enter data in the blank.')
                # show error and add new student
                return render_to_response('add_student_form.html',\
{'errors': errors, 'URL': url, 'USER': userDetail})


#####################  REMOVE STUDENT (by Sombut Poolsawat)##################
def removeStudent_form(request):
    # Check authenticate.
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    t = get_template('remove_student_form.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


def removeStudent(request):
    # Check authenticate.
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        errors = []  # Variable declarations : error type list
        if 'id_student' in request.GET and request.GET['id_student'] \
        and 'firstname' in request.GET and request.GET['firstname'] \
        and 'lastname' in request.GET and request.GET['lastname']:
                # Keep value received
                id_student_in = request.GET['id_student']
                firstName_in = request.GET['firstname']
                lastname_in = request.GET['lastname']
                # check student want remove to be valid.
                if DetailStudent.objects.filter(studentID=id_student_in) \
                and DetailStudent.objects.filter(firstName=firstName_in) \
                and DetailStudent.objects.filter(lastName=lastname_in):
                    userDetail = request.user
                    # delete student
                    DetailStudent.objects.filter(\
                    studentID=id_student_in).delete()
                    url = request.get_host()
                    # show remove student result
                    return render_to_response('remove_student_result.html',\
                    {'URL': url, 'studentID': id_student_in, \
                    'firstName': firstName_in, 'lastname': lastname_in, \
                    'USER': userDetail})
                # Student want remove not match
                else:
                    userDetail = request.user
                    url = request.get_host()
                    errors.append('Student does not match!!')
                    # show error and remove new student
                    return render_to_response('remove_student_form.html',\
                    {'errors': errors, 'URL': url, 'USER': userDetail})
        # the data get incomplete
        else:
                userDetail = request.user
                url = request.get_host()
                errors.append('Please enter data in the blank.')
                # show error and remove new student
                return render_to_response('remove_student_form.html',\
                {'errors': errors, 'URL': url, 'USER': userDetail})


##############  DETAIL STUDENTS ALL SECTION  (by Waranya Buapha) ##############
def viewsStudent_form(request):
    count = 0
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    Student = DetailStudent.objects.all()
    t = get_template('views_student_detail.html')
    html = t.render(Context({'URL': url, \
    'STUDENT': Student, 'USER': userDetail}))
    return HttpResponse(html)


def viewsStudent(request):
    i = 0
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        userDetail = request.user
        url = request.get_host()
        Student = DetailStudent.objects.all()
        if(Student != "null"):
                DetailStudent.objects.filter(\
                studentID=request.GET['button']).delete()
        return render_to_response('views_student_detail.html',\
        {'URL': url, 'STUDENT': Student, 'USER': userDetail})


####################  ADD LAB SCORE (by Waranya Buapha) #######################
def addLabScore_form(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    t = get_template('add_lab_score_form.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


def addLabScore(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        errors = []  # Variable declarations : error type list
        if 'id_student' in request.GET and request.GET['id_student'] \
        and 'lab' in request.GET and request.GET['lab']:
                # Keep value received
                id_student_in = request.GET['id_student']
                lab_in = request.GET['lab']
                labINT = float(lab_in)
                if labINT >= 0 and labINT <= 30:
                    if DetailStudent.objects.filter(studentID=id_student_in):
                        DetailStudent.objects.filter(\
                        studentID=id_student_in).update(labScore=lab_in)
                        userDetail = request.user
                        url = request.get_host()
                        return render_to_response('add_lab_result.html', \
                        {'URL': url, 'studentID': id_student_in, \
                        'lab': lab_in, 'USER': userDetail})
                    else:
                        userDetail = request.user
                        url = request.get_host()
                        errors.append('Student does not match!!')
                        return render_to_response('add_lab_score_form.html', \
                        {'errors': errors, 'URL': url, 'USER': userDetail})
                else:
                    userDetail = request.user
                    url = request.get_host()
                    errors.append('Score over the edge.')
                    return render_to_response('add_lab_score_form.html', \
                    {'errors': errors, 'URL': url, 'USER': userDetail})
        else:
                userDetail = request.user
                url = request.get_host()
                errors.append('Please enter data in the blank.')
                return render_to_response('add_lab_score_form.html', \
                {'errors': errors, 'URL': url, 'USER': userDetail})


################  ADD MIDTERM SCORE (by Sombut Poolsawat)#####################
def addMidScore_form(request):
    # Check authenticate.
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    t = get_template('add_mid_score_form.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


def addMidScore(request):
    # Check authenticate.
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        errors = []  # Variable declarations : error type list
        if 'id_student' in request.GET and request.GET['id_student']  \
        and 'midterm' in request.GET and request.GET['midterm']:
                # Keep value received
                id_student_in = request.GET['id_student']
                midterm_in = request.GET['midterm']
                # catch type
                midtermINT = float(midterm_in)
                # score midterm in the range 0-30
                if midtermINT >= 0 and midtermINT <= 30:
                    # check student want add score midterm to be valid.
                    if DetailStudent.objects.filter(studentID=id_student_in):
                        # update score midterm
                        DetailStudent.objects.filter(\
                        studentID=id_student_in).update(midScore=midterm_in)
                        userDetail = request.user
                        url = request.get_host()
                        # show add score midterm result
                        return render_to_response('add_midterm_result.html', \
                        {'URL': url, 'studentID': id_student_in, \
                        'midterm': midterm_in, 'USER': userDetail})
                    else:
                        userDetail = request.user
                        url = request.get_host()
                        errors.append('Student does not match!!')
                        # show error and add new score midterm
                        return render_to_response('add_mid_score_form.html', \
                        {'errors': errors, 'URL': url, 'USER': userDetail})
                else:
                    userDetail = request.user
                    url = request.get_host()
                    errors.append('Score over the edge.')
                    # show error and add new score midterm
                    return render_to_response('add_mid_score_form.html', \
                    {'errors': errors, 'URL': url, 'USER': userDetail})
        else:
                userDetail = request.user
                url = request.get_host()
                errors.append('Please enter data in the blank.')
                # show error and add new score midterm
                return render_to_response('add_mid_score_form.html', \
                {'errors': errors, 'URL': url, 'USER': userDetail})


####################  ADD FINAl SCORE (by Sombut Poolsawat)####################
def addFinalScore_form(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form_err.html')
    userDetail = request.user
    url = request.get_host()
    t = get_template('add_final_score_form.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


def addFinalScore(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        errors = []  # Variable declarations : error type list
        if 'id_student' in request.GET and request.GET['id_student'] \
        and 'final' in request.GET and request.GET['final']:
                # Keep value received
                id_student_in = request.GET['id_student']
                final_in = request.GET['final']
                # catch type
                finalINT = float(final_in)
                # score final in the range 0-40
                if finalINT >= 0 and finalINT <= 40:
                    # check student want add score final to be valid.
                    if DetailStudent.objects.filter(studentID=id_student_in):
                        userDetail = request.user
                        # update score final
                        DetailStudent.objects.filter(\
                        studentID=id_student_in).update(finalScore=final_in)
                        url = request.get_host()
                        # show add score final result
                        return render_to_response('add_final_result.html', \
                        {'URL': url, 'studentID': id_student_in, \
                        'final': final_in, 'USER': userDetail})
                    else:
                        userDetail = request.user
                        url = request.get_host()
                        errors.append('Student does not match!!')
                        # show error and add new score final
                        return render_to_response(\
                        'add_final_score_form.html',\
                        {'errors': errors, 'URL': url, 'USER': userDetail})
                else:
                    userDetail = request.user
                    url = request.get_host()
                    errors.append('Score over the edge.')
                    # show error and add new score final
                    return render_to_response('add_final_score_form.html', \
                    {'errors': errors, 'URL': url, 'USER': userDetail})
        else:
                userDetail = request.user
                url = request.get_host()
                errors.append('Please enter data in the blank.')
                # show error and add new score final
                return render_to_response('add_final_score_form.html', \
                {'errors': errors, 'URL': url, 'USER': userDetail})


#################  Calculate Grade (by narongsak luansrimongkon) ##############
def calculateGrade(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    Student = DetailStudent.objects.all()

    for index in range(len(Student)):
        id_student_in = Student[index].studentID
        mid = Student[index].midScore
        final = Student[index].finalScore
        lab = Student[index].labScore
        if(final) != 'null' and (mid) != 'null' and (lab) != 'null':
                totalScore = float(mid) + float(final) + float(lab)
                if totalScore != 0:
                    if totalScore >= 80:
                        gradeScore = 'A'
                    elif totalScore >= 75 and totalScore < 80:
                        gradeScore = 'B+'
                    elif totalScore >= 70 and totalScore < 75:
                        gradeScore = 'B'
                    elif totalScore >= 65 and totalScore < 70:
                        gradeScore = 'C+'
                    elif totalScore >= 60 and totalScore < 65:
                        gradeScore = 'C'
                    elif totalScore >= 55 and totalScore < 60:
                        gradeScore = 'D+'
                    elif totalScore >= 50 and totalScore < 55:
                        gradeScore = 'D'
                    else:
                        gradeScore = 'F'
                DetailStudent.objects.filter(studentID=id_student_in).update(\
                totalScore=totalScore, gradeScore=gradeScore)
    Student = DetailStudent.objects.all()
    t = get_template('calculation_grade_form.html')
    html = t.render(Context({'URL': url, 'STUDENT': Student, \
    'USER': userDetail}))
    return HttpResponse(html)


###################  Show Grade  (by narongsak luansrimongkon) ################
def showGrade(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form_err.html')
    userDetail = request.user
    url = request.get_host()
    Student = DetailStudent.objects.all()
    t = get_template('show_grade_form.html')
    html = t.render(Context({'URL': url, 'STUDENT': Student, \
    'USER': userDetail}))
    return HttpResponse(html)


def student_form(request):
    url = request.get_host()
    t = get_template('student_form.html')
    html = t.render(Context({'URL': url}))
    return HttpResponse(html)


def student_show_grade_form(request):
    errors = []  # Variable declarations : error type list
    if 'id_student' in request.GET and request.GET['id_student']:
        id_student_in = request.GET['id_student']
        if ReportStudent.objects.filter(studentID=id_student_in):
            Student = ReportStudent.objects.filter(studentID=id_student_in)
            url = request.get_host()
            t = get_template('student_show_grade_form.html')
            html = t.render(Context({'URL': url, 'STUDENT': Student}))
            return HttpResponse(html)
        else:
            errors.append('Please check ID STUDENT')
            url = request.get_host()
            t = get_template('student_form.html')
            html = t.render(Context({'URL': url, 'errors': errors}))
            return HttpResponse(html)
    else:
        errors.append('Please enter ID STUDENT in the blank!!')
        url = request.get_host()
        t = get_template('student_form.html')
        html = t.render(Context({'URL': url, 'errors': errors}))
        return HttpResponse(html)


def showGradeStudent(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form_err.html')
    userDetail = request.user
    url = request.get_host()
    Student = DetailStudent.objects.all()
    deleteData = ReportStudent.objects.all()
    deleteData.delete()
    for Student in Student:
        studentID_input = Student.studentID
        firstName_input = Student.firstName
        lastName_input = Student.lastName
        totalScore_input = Student.totalScore
        gradeScore_input = Student.gradeScore
        section_input = Student.section
        report = ReportStudent.objects.create(studentID=studentID_input, \
        firstName=firstName_input, lastName=lastName_input, \
        totalScore=totalScore_input, gradeScore=gradeScore_input, \
        section=section_input)
        report.save()
    reportData = ReportStudent.objects.all()
    t = get_template('show_grade_student_form.html')
    html = t.render(Context({'URL': url, 'STUDENT': reportData, \
    'USER': userDetail}))
    return HttpResponse(html)


#################### report (by Tamakorn Leangpuksa )##########################
def sendGrade(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    t = get_template('sent_grade_form.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


def report(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        errors = []  # Variable declarations : error type list
        tmp_ID = []
        tmp_name = []
        tmp_last = []
        tmp_grade = []
        if 'section' in request.GET and request.GET['section']:
                section = request.GET['section']
                if DetailStudent.objects.filter(section=section):
                    Data = DetailStudent.objects.filter(section=section)
                    for objects in Data:
                        tmp_ID.append(objects.studentID)
                        tmp_name.append(objects.firstName)
                        tmp_last.append(objects.lastName)
                        tmp_grade.append(objects.gradeScore)
                        files = open('report/report.csv', 'w')
                    for i in range(len(tmp_ID)):
                        files.write(str(tmp_ID[i]) + "," + str(tmp_name[i]) +\
"," + str(tmp_last[i]) + "," + str(tmp_grade[i]) + "\n")
                    files.close()
                    userDetail = request.user
                    url = request.get_host()
                    return render_to_response('report-complete.html', \
                    {'URL': url, 'USER': userDetail})
                else:
                    userDetail = request.user
                    url = request.get_host()
                    errors.append('Section does not match!!!')
                    return render_to_response('report-error.html', \
                    {'errorabass': errors, 'URL': url, 'USER': userDetail})
        else:
            userDetail = request.user
            url = request.get_host()
            errors.append('Section not found !!!')
            return render_to_response('report-error.html', \
            {'errorabass': errors, 'URL': url, 'USER': userDetail})


def report_complete(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        url = request.get_host()
        userDetail = request.user
        t = get_template('report-complete.html.html')
        html = t.render(Context({'URL': url, 'USER': userDetail}))
        return HttpResponse(html)


def report_error(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        url = request.get_host()
    userDetail = request.user
    t = get_template('report-error.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


######################## SVG GRAPH (by Anan Kamkemkeaw)########################
def make_graph(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        errors = []  # Variable declarations : error type list
        if 'section' in request.GET and request.GET['section']:
            section = request.GET['section']
            Va = 0   # valiable for count numbergrade
            Vbp = 0
            Vb = 0
            Vcp = 0
            Vc = 0
            Vdp = 0
            Vd = 0
            Vf = 0
            count = 0
            # check section match
            if DetailStudent.objects.filter(section=section):
                MAX = 0.0
                MIN = 100.0
                tmp = 0.0
                # store value in data
                Data = DetailStudent.objects.filter(section=section)
                # for count number grade
                for objects in Data:  # for count number grade
                        if str(objects.totalScore) != 'null':
                            tmp += float(objects.totalScore)
                            if float(objects.totalScore) > MAX:
                                MAX = float(objects.totalScore)
                            if float(objects.totalScore) < MIN:
                                MIN = float(objects.totalScore)
                        count += 1
                        if str(objects.gradeScore) == 'A':
                            Va += 1
                        elif str(objects.gradeScore) == 'B+':
                            Vbp += 1
                        elif str(objects.gradeScore) == 'B':
                            Vb += 1
                        elif str(objects.gradeScore) == 'C+':
                            Vcp += 1
                        elif str(objects.gradeScore) == 'C':
                            Vc += 1
                        elif str(objects.gradeScore) == 'D+':
                            Vdp += 1
                        elif str(objects.gradeScore) == 'D':
                            Vd += 1
                        elif str(objects.gradeScore) == 'F':
                            Vf += 1
                        else:
                            count += -1
                Aver = float(tmp) / float(count)   # solution average persen
                r = 180.0                        # DETERMINE REDIAN
                # solution grade persen
                A = (float(Va) / float(count)) * 100.0
                BP = (float(Vbp) / float(count)) * 100.0
                B = (float(Vb) / float(count)) * 100.0
                CP = (float(Vcp) / float(count)) * 100.0
                C = (float(Vc) / float(count)) * 100.0
                DP = (float(Vdp) / float(count)) * 100.0
                D = (float(Vd) / float(count)) * 100.0
                F = (float(Vf) / float(count)) * 100.0
                f = open('templates/showgraph.html', 'w')     # make file html
                f.write('<?xml version="1.0" encoding="utf-8" \
standalone="no"?>')   # html code
                f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 \
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">')
                f.write('<html xmlns="http://www.w3.org/1999/xhtml">')
                f.write('<head><meta http-equiv="Content-Type" content="\
text/html; charset=iso-8859-1" /><title>Teacher</title><style type="text/css">\
<!--.style1 {color: #FFFFFF}--></style></head>')
                f.write('<body><table width="200" border="2" \
bordercolor="#FFFFFF">')
                f.write('<tr><td colspan="2"><div align="center"><img src=\
"/media/banner_2.jpg" alt="baner" width="1280" height="158" /></div>')
                f.write('<div align="right">You are logged in as {{USER}} \
(<a  href="http://{{ URL }}/teacher/logout">Logout</a>)</div></td></tr>')
                f.write('<tr><td width="277" height="39" bgcolor="#3B5999">\
<div align="center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}\
/teacher/add_student_form" class="style1">ADD STUDENT </a></div></div></td>')
                f.write('<td width="997" rowspan="9"><div align="center">\
<table width="636" height="258" border="0"><tr><td width="630"><div \
align="center">')
                f.write('<svg width="1200px" height="550px" xmlns="http\
://www.w3.org/2000/svg" version="1.1">\n')   # SVG code
                f.write('<defs>\n<filter id="dropshadow" width="120%" \
height="120%">\n<feGaussianBlur stdDeviation="4"/>\n</filter>\n\
</defs>\n')      # smoke valiable
                f.write('<text x="150" y="50" style="font-family: \
verdana, arial, sans-serif; font-size: 36; font-weight: bold; fill: \
#0099ff; stroke: black; stroke-width: 1">Grade Graph</text>\n')  # Text head
                f.write('<ellipse cx="205" cy="245" rx="180" ry="180" style=\
"fill: black; fill-opacity:0.6;	stroke:none; filter:url(#dropshadow)"\
/>\n')   # shadow
    # this check grade more 40% because It will be over 180 seta and will error
                if A > 49:
                    A1 = A / 2
                    X2 = port_tranfrom_X(A)
                    Y2 = port_tranfrom_Y(A)
                    X1 = port_tranfrom_X(A1)
                    Y1 = port_tranfrom_Y(A1)
                    # path to make pie graph
                    f.write('<path d="M200,240 L20,240 A180,180 0 0,1 ' + \
str(int(X1) + 20) + ',' + str(int(Y1) + 60) + ' z" style="fill:#0000FF; \
fill-opacity: 1; stroke:#0000FF; stroke-width: 1"/>\n')
                    f.write('<path d="M200,240 L' + str(int(X1) + 20) + ',' \
+ str(int(Y1) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + \
str(int(Y2) + 60) + ' z" style="fill:#0000FF; fill-opacity: 1; stroke:\
#0000FF; stroke-width: 1"/>\n')  # path to make pie graph
                else:
                    X2 = port_tranfrom_X(A)
                    Y2 = port_tranfrom_Y(A)
                    f.write('<path d="M200,240 L20,240 A180,180 0 0,1 ' \
+ str(int(X2) + 20) + ',' + str(int(Y2) + 60) + ' z" style="fill:#0000FF; fill\
-opacity: 1; stroke:#0000FF; stroke-width: 1"/>\n')  # path to make pie graph
    # this check grade more 40% because It will be over 180 seta and will error
                if BP > 49:
                    BP1 = BP / 2
                    X2 = port_tranfrom_X(BP + A)
                    Y2 = port_tranfrom_Y(BP + A)
                    X1 = port_tranfrom_X(BP1 + A)
                    Y1 = port_tranfrom_Y(BP1 + A)
                    X0 = port_tranfrom_X(A)
                    Y0 = port_tranfrom_Y(A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' \
+ str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X1 + 20)) + ',' + str(\
int(Y1) + 60) + ' z" style="fill:#00FFFF; fill-opacity: 1; stroke:#00FFFF; \
stroke-width: 1"/>\n')
                    f.write('<path d="M200,240 L' + str(int(X1) + 20) + ',' \
+ str(int(Y1) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(\
int(Y2) + 60) + ' z" style="fill:#00FFFF; fill-opacity: 1; stroke:#00FFFF; \
stroke-width: 1"/>\n')
                else:
                    X2 = port_tranfrom_X(BP + A)
                    Y2 = port_tranfrom_Y(BP + A)
                    X0 = port_tranfrom_X(A)
                    Y0 = port_tranfrom_Y(A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' \
+ str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(\
Y2) + 60) + ' z" style="fill:#00FFFF; fill-opacity: 1; stroke:#00FFFF; \
stroke-width: 1"/>\n')
    # this check grade more 40% because It will be over 180 seta and will error
                if B > 49:
                    B1 = B / 2
                    X2 = port_tranfrom_X(B + BP + A)
                    Y2 = port_tranfrom_Y(B + BP + A)
                    X1 = port_tranfrom_X(B1 + BP + A)
                    Y1 = port_tranfrom_Y(B1 + BP + A)
                    X0 = port_tranfrom_X(BP + A)
                    Y0 = port_tranfrom_Y(BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X1 + 20)) + ',' + str(int(Y1)\
 + 60) + ' z" style="fill:#00FF00; fill-opacity: 1; stroke:#00FF00; \
stroke-width: 1"/>\n')
                    f.write('<path d="M200,240 L' + str(int(X1) + 20) + ',' \
+ str(int(Y1) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(\
int(Y2) + 60) + ' z" style="fill:#00FF00; fill-opacity: 1; stroke:#00FF00; \
stroke-width: 1"/>\n')
                else:
                    X2 = port_tranfrom_X(B + BP + A)
                    Y2 = port_tranfrom_Y(B + BP + A)
                    X0 = port_tranfrom_X(BP + A)
                    Y0 = port_tranfrom_Y(BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#00FF00; fill-opacity: 1; stroke:#00FF00; \
stroke-width: 1"/>\n')
    # this check grade more 40% because It will be over 180 seta and will error
                if CP > 49:
                    CP1 = CP / 2
                    X2 = port_tranfrom_X(CP + B + BP + A)
                    Y2 = port_tranfrom_Y(CP + B + BP + A)
                    X1 = port_tranfrom_X(CP1 + B + BP + A)
                    Y1 = port_tranfrom_Y(CP1 + B + BP + A)
                    X0 = port_tranfrom_X(B + BP + A)
                    Y0 = port_tranfrom_Y(B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X1 + 20)) + ',' + str(int(Y1)\
 + 60) + ' z" style="fill:#FFFF00; fill-opacity: 1; stroke:#FFFF00; \
stroke-width: 1"/>\n')
                    f.write('<path d="M200,240 L' + str(int(X1) + 20) + ',' + \
str(int(Y1) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FFFF00; fill-opacity: 1; stroke:#FFFF00; \
stroke-width: 1"/>\n')
                else:
                    X2 = port_tranfrom_X(CP + B + BP + A)
                    Y2 = port_tranfrom_Y(CP + B + BP + A)
                    X0 = port_tranfrom_X(B + BP + A)
                    Y0 = port_tranfrom_Y(B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FFFF00; fill-opacity: 1; stroke:#FFFF00; \
stroke-width: 1"/>\n')
    # this check grade more 40% because It will be over 180 seta and will error
                if C > 49:
                    C1 = C / 2
                    X2 = port_tranfrom_X(C + CP + B + BP + A)
                    Y2 = port_tranfrom_Y(C + CP + B + BP + A)
                    X1 = port_tranfrom_X(C1 + CP + B + BP + A)
                    Y1 = port_tranfrom_Y(C1 + CP + B + BP + A)
                    X0 = port_tranfrom_X(CP + B + BP + A)
                    Y0 = port_tranfrom_Y(CP + B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X1 + 20)) + ',' + str(int(Y1)\
 + 60) + ' z" style="fill:#FFA500; fill-opacity: 1; stroke:#FFA500;\
 stroke-width: 1"/>\n')
                    f.write('<path d="M200,240 L' + str(int(X1) + 20) + ',' + \
str(int(Y1) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FFA500; fill-opacity: 1; stroke:#FFA500; \
stroke-width: 1"/>\n')
                else:
                    X2 = port_tranfrom_X(C + CP + B + BP + A)
                    Y2 = port_tranfrom_Y(C + CP + B + BP + A)
                    X0 = port_tranfrom_X(CP + B + BP + A)
                    Y0 = port_tranfrom_Y(CP + B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FFA500; fill-opacity: 1; stroke:#FFA500; \
stroke-width: 1"/>\n')
    # this check grade more 40% because It will be over 180 seta and will error
                if DP > 49:
                    DP1 = DP / 2
                    X2 = port_tranfrom_X(DP + C + CP + B + BP + A)
                    Y2 = port_tranfrom_Y(DP + C + CP + B + BP + A)
                    X1 = port_tranfrom_X(DP1 + C + CP + B + BP + A)
                    Y1 = port_tranfrom_Y(DP1 + C + CP + B + BP + A)
                    X0 = port_tranfrom_X(C + CP + B + BP + A)
                    Y0 = port_tranfrom_Y(C + CP + B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X1 + 20)) + ',' + str(int(Y1)\
 + 60) + ' z" style="fill:#FF0000; fill-opacity: 1; stroke:#FF0000; \
stroke-width: 1"/>\n')
                    f.write('<path d="M200,240 L' + str(int(X1) + 20) + ',' + \
str(int(Y1) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FF0000; fill-opacity: 1; stroke:#FF0000; \
stroke-width: 1"/>\n')
                else:
                    X2 = port_tranfrom_X(DP + C + CP + B + BP + A)
                    Y2 = port_tranfrom_Y(DP + C + CP + B + BP + A)
                    X0 = port_tranfrom_X(C + CP + B + BP + A)
                    Y0 = port_tranfrom_Y(C + CP + B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FF0000; fill-opacity: 1; stroke:#FF0000;\
 stroke-width: 1"/>\n')
   # this check grade more 40% because It will be over 180 seta and will error
                if D > 49:
                    D1 = D / 2
                    X2 = port_tranfrom_X(D + DP + C + CP + B + BP + A)
                    Y2 = port_tranfrom_Y(D + DP + C + CP + B + BP + A)
                    X1 = port_tranfrom_X(D1 + DP + C + CP + B + BP + A)
                    Y1 = port_tranfrom_Y(D1 + DP + C + CP + B + BP + A)
                    X0 = port_tranfrom_X(DP + C + CP + B + BP + A)
                    Y0 = port_tranfrom_Y(DP + C + CP + B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X1 + 20)) + ',' + str(int(Y1)\
 + 60) + ' z" style="fill:#FFB5C5; fill-opacity: 1; stroke:#FFB5C5; \
stroke-width: 1"/>\n')
                    f.write('<path d="M200,240 L' + str(int(X1) + 20) + ',' + \
str(int(Y1) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FFB5C5; fill-opacity: 1; stroke:#FFB5C5; \
stroke-width: 1"/>\n')
                else:
                    X2 = port_tranfrom_X(D + DP + C + CP + B + BP + A)
                    Y2 = port_tranfrom_Y(D + DP + C + CP + B + BP + A)
                    X0 = port_tranfrom_X(DP + C + CP + B + BP + A)
                    Y0 = port_tranfrom_Y(DP + C + CP + B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FFB5C5; fill-opacity: 1; stroke:#FFB5C5; \
stroke-width: 1"/>\n')
    # this check grade more 40% because It will be over 180 seta and will error
                if F > 49:
                    F1 = F / 2
                    X2 = port_tranfrom_X(F + D + DP + C + CP + B + BP + A)
                    Y2 = port_tranfrom_Y(F + D + DP + C + CP + B + BP + A)
                    X1 = port_tranfrom_X(F1 + D + DP + C + CP + B + BP + A)
                    Y1 = port_tranfrom_Y(F1 + D + DP + C + CP + B + BP + A)
                    X0 = port_tranfrom_X(D + DP + C + CP + B + BP + A)
                    Y0 = port_tranfrom_Y(D + DP + C + CP + B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X1 + 20)) + ',' + str(int(Y1)\
 + 60) + ' z" style="fill:#FFB5C5; fill-opacity: 1; stroke:#FFB5C5; \
stroke-width: 1"/>\n')
                    f.write('<path d="M200,240 L' + str(int(X1) + 20) + ',' + \
str(int(Y1) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FFB5C5; fill-opacity: 1; stroke:#FFB5C5; \
stroke-width: 1"/>\n')
                else:
                    X2 = port_tranfrom_X(F + D + DP + C + CP + B + BP + A)
                    Y2 = port_tranfrom_Y(F + D + DP + C + CP + B + BP + A)
                    X0 = port_tranfrom_X(D + DP + C + CP + B + BP + A)
                    Y0 = port_tranfrom_Y(D + DP + C + CP + B + BP + A)
                    f.write('<path d="M200,240 L' + str(int(X0) + 20) + ',' + \
str(int(Y0) + 60) + ' A180,180 0 0,1 ' + str(int(X2 + 20)) + ',' + str(int(Y2)\
 + 60) + ' z" style="fill:#FFB5C5; fill-opacity: 1; stroke:#FFB5C5; \
stroke-width: 1"/>\n')
                f.write('<rect x="470" y="50" width="30" height="20" \
style="stroke-linejoin: mitre; stroke-width: 2; stroke: black; fill: \
#0000FF"/>\n')  # rectan pote
                f.write('<text x="520" y="66" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">Grade A  : ' + \
str(A) + '%</text>\n')  # text Persen
                f.write('<rect x="470" y="90" width="30" height="20" \
style="\stroke-linejoin: mitre; stroke-width: 2; stroke: black; fill: \
#00FFFF"/>\n')  # rectan pote
                f.write('<text x="520" y="106" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">Grade B+ : ' + \
str(BP) + '%</text>\n')  # text Persen
                f.write('<rect x="470" y="130" width="30" height="20" \
style="stroke-linejoin: mitre; stroke-width: 2; stroke: black; fill: \
#00FF00"/>\n')  # rectan pote
                f.write('<text x="520" y="146" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">Grade B  : ' + \
str(B) + '%</text>\n')  # text Persen
                f.write('<rect x="470" y="170" width="30" height="20" \
style="stroke-linejoin: mitre; stroke-width: 2; stroke: black; fill: \
#FFFF00"/>\n')  # rectan pote
                f.write('<text x="520" y="186" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">Grade C+ : ' + \
str(CP) + '%</text>\n')  # text Persen
                f.write('<rect x="470" y="210" width="30" height="20" \
style="stroke-linejoin: mitre; stroke-width: 2; stroke: black; fill: \
#FFA500"/>\n')  # rectan pote
                f.write('<text x="520" y="226" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">Grade C  : ' + \
str(C) + '%</text>\n')  # text Persen
                f.write('<rect x="470" y="250" width="30" height="20" \
style="stroke-linejoin: mitre; stroke-width: 2; stroke: black; fill: \
#FF0000"/>\n')  # rectan pote
                f.write('<text x="520" y="266" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">Grade D+ : ' + \
str(DP) + '%</text>\n')  # text Persen
                f.write('<rect x="470" y="290" width="30" height="20" \
style="stroke-linejoin: mitre; stroke-width: 2; stroke: black; fill: \
#FFB5C5"/>\n')  # rectan pote
                f.write('<text x="520" y="306" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">Grade D  : ' + \
str(D) + '%</text>\n')  # text Persen
                f.write('<rect x="470" y="330" width="30" height="20" \
style="stroke-linejoin: mitre; stroke-width: 2; stroke: black; fill: \
#FF00FF"/>\n')  # rectan pote
                f.write('<text x="520" y="346" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">Grade F  : ' + \
str(F) + '%</text>\n')  # text Persen
                f.write('<text x="450" y="386" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">Number of \
students in section ' + str(count) + \
' Student</text>\n')  # text student number Persen
                f.write('<text x="450" y="426" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">MAX score : ' + \
str(MAX) + ' point</text>\n')  # text max Persen
                f.write('<text x="450" y="466" style="font-family:verdana, \
arial, sans-serif; font-size: 14; fill: black; stroke: none">MIN score : ' + \
str(MIN) + ' point</text>\n')  # text min Persen
                f.write('<text x="450" y="506" style="font-family:verdana, \
arial, \sans-serif; font-size: 14; fill: black; stroke: none">Average   : ' + \
str(Aver) + ' point</text><nobr>')  # text average Persenf.write('</svg>\n')
                f.write('<script>function fbs_click() {u=location.href;t=\
document.title;window.open(''http://www.facebook.com/sharer.php?u=''\
+encodeURIComponent(u)+''&t=''+encodeURIComponent(t),''sharer'',''toolbar=0,\
status=0,width=626,height=436'');return false;}</script><style> html \
.fb_share_link { padding:2px 0 0 20px; height:16px; background:url\
(http://static.ak.fbcdn.net/rsrc.php/z39E0/hash/ya8q506x.gif) no-repeat \
top left; }</style><a href="http://www.facebook.com/share.php?u=\
http://127.0.0.1:8000/svg/" onclick="return fbs_click()" target="_blank" \
class="fb_share_link">Share on Facebook</a>')
                f.write('</svg>')  # end svg
                f.write('</div></td></tr></table></div></td></tr><tr>\
<td height="40" bgcolor="#3B5999"><div align="center" \
class="style1">')  # htma code
                f.write('<div align="center"><a href="http://{{ URL }}\
/teacher/remove_student_form" class="style1">REMOVE STUDENT </a></div>\
</div></td></tr><tr>')
                f.write('<td height="40" bgcolor="#3B5999"><div align=\
"center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}\
/teacher/views_student_form" class="style1">VIEWS STUDENT DETAIL</a>\
</div></div></td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}\/\
teacher/add_all_form" class="style1">ADD ALL SCORE </a></div></div></td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}/\
teacher/add_lab_form" class="style1">ADD LAB SCORE </a></div></div></td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}/teacher\
/add_mid_form" class="style1">ADD MIDTERM SCORE </a></div></div></td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center"><span class="style1">')
                f.write('<a href="http://{{ URL }}/teacher/add_final_form" \
class="style1">ADD FINAL SCORE </a></span></div></td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}/teacher\
/calculate_grade" class="style1">CALCULATION GRADE </a></div></div></td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}/teacher\
/show_grade" class="style1">SHOW GRADE FOR STUDENT </a></div></div></td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center"><span class="style1">')
                f.write('<a href="http://{{ URL }}/teacher/upload_file" class=\
"style1">UPLOAD FILE </a></span></div></td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}/teacher\
/send_grade" class="style1">SENT GRADE TO   DEPARTMENT</a></div></div>\
</td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}/teacher\
/show_grade_grapht" class="style1">GRADE GRAPH</a></div></div></td></tr>')
                f.write('<tr><td height="40" bgcolor="#3B5999">\
<div align="center" class="style1">')
                f.write('<div align="center"><a href="http://{{ URL }}/teacher\
/logout" class="style1">LOGOUT</a></div></div></td></tr></table><div \
align="center"></div><p>&nbsp;</p></body></html>')  # end htmal code
                f.close()
                userDetail = request.user
                url = request.get_host()
                t = get_template('svg-complete.html')
                html = t.render(Context({'URL': url, 'USER': userDetail}))
                return HttpResponse(html)
            else:
                userDetail = request.user
                url = request.get_host()
                errors.append('section does not match!!')
                #show error and add new score midterm
                return render_to_response('svg-error.html', \
{'errors': errors, 'URL': url, 'USER': userDetail})
        else:  # if section not match
            userDetail = request.user
            url = request.get_host()
            errors.append('Section not found !!!')
            return render_to_response('svg-error.html', \
{'errors': errors, 'URL': url, 'USER': userDetail})


def port_tranfrom_X(gread):  # fungtion to solution x point
    X = 180.0 * (math.cos(math.radians(360.0 * (float(gread) / 100.0))))
    if X < 0:
        X = (X * (-1.0)) + 180.0
    else:
        X = 180.0 - X
    return X


def port_tranfrom_Y(gread):  # fungtion to solution x point
    Y = 180.0 * (math.sin(math.radians(360.0 * (float(gread) / 100.0))))
    if Y < 0:
        Y = (Y * (-1.0)) + 180.0
    else:
        Y = 180.0 - Y
    return Y


def show_grade_graph(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    t = get_template('show_graph.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


def show_graph(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    t = get_template('svg-complete.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


def svg(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    t = get_template('showgraph.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


####################  UPLOAD FILE (by Anan Kamkemkeaw)#########################
def uploadFile(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    userDetail = request.user
    url = request.get_host()
    t = get_template('upload_file.html')
    html = t.render(Context({'URL': url, 'USER': userDetail}))
    return HttpResponse(html)


def upload(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        errors = []  # list store error student ID not match
        complete = []  # list store student ID  match
        userDetail = request.user
        # if file found
        if 'files' in request.FILES and request.FILES['files']:
                files = request.FILES['files']
                create = UploadFiles.objects.create(\
                name=userDetail, files=files)  # create file to media/uplaod
                create.save()
                for line in files:  # for to loop line and split comma
                    s = line.split(',')
                    labScore = float(s[1]) * 0.3
                    # check student ID match
                    if DetailStudent.objects.filter(studentID=s[0]):
                        DetailStudent.objects.filter(studentID=s[0]).update(\
                        labScore=str(int(labScore)))  # update lab score
                        # store student ID complete
                        complete.append(str(int(s[0])))
                    else:
                        errors.append(str(int(s[0])))  # store student ID error
                userDetail = request.user
                url = request.get_host()
                return render_to_response('upload-status.html', \
                {'errors': errors, 'complete': complete, 'URL': url, \
                'USER': userDetail})
        else:
                userDetail = request.user
                url = request.get_host()
                errors.append('File not found !!!')
                return render_to_response('upload-error.html', \
                {'errors': errors, 'URL': url, 'USER': userDetail})


def upload_complete(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        url = request.get_host()
        userDetail = request.user
        t = get_template('upload-status.html')
        html = t.render(Context({'URL': url, 'USER': userDetail}))
        return HttpResponse(html)


def upload_error(request):
    if not request.user.is_authenticated():
        return render_to_response('teacher_form.html')
    else:
        url = request.get_host()
        userDetail = request.user
        t = get_template('upload-error.html')
        html = t.render(Context({'URL': url, 'USER': userDetail}))
        return HttpResponse(html)


###################### LOGOUT (by Porngsathorn Surikan)########################
def logout_view(request):
    logout(request)
    url = request.get_host()
    t = get_template('main.html')
    html = t.render(Context({'URL': url}))
    return HttpResponse(html)
